#include <unistd.h> 
#include <stdio.h> 
#include <sys/ipc.h> 
#include "shm_segment.h" 
#include <string.h> 
#include <stdlib.h> 
#include <sys/shm.h> 
#include <errno.h> 
#include <signal.h> 
#include <sys/wait.h> 

int main(int argc, char **argv) {
    int ret = shmget(static_cast<key_t>(123456), sizeof(int), 0666 | IPC_CREAT | IPC_EXCL);
    printf("key: %x\n", 123456);
    if (ret == -1) {
        printf("%s %d:shmget error\n", __FILE__, __LINE__);
        return -1;
    }

    int shmid = ret;

    int* shm_addr1 = (int *)shmat(shmid, nullptr, 0);
    if (reinterpret_cast<intptr_t>(shm_addr1) == -1) {
        printf("shmat1 error<%s>.\n", strerror(errno));
        return -1;
    }

    int shmid2 = shmget(static_cast<key_t>(123456), 0, 0666);
    if (ret == -1) {
        printf("%s %d:shmget error\n", __FILE__, __LINE__);
        return -1;
    }

    int* shm_addr2 = (int *)shmat(shmid2, nullptr, 0);
    if (reinterpret_cast<intptr_t>(shm_addr2) == -1) {
        printf("shmat2 error<%s>.\n", strerror(errno));
        return -1;
    }

    if (shmdt(shm_addr1) < 0)
      printf("detach shm_addr1 error<%s>\n", strerror(errno));

    if (shmdt(shm_addr2) < 0)
      printf("detach shm_addr2 error<%s>\n", strerror(errno));

    getchar();

    printf("shmmid1:%d shmid2:%d\n", shmid, shmid2);
    ret = shmctl(shmid, IPC_RMID, nullptr);
    if (ret == -1) {
        printf("%s %d:shmctl error\n", __FILE__, __LINE__);
        return -1;
    }

    getchar();

    ret = shmctl(shmid2, IPC_RMID, nullptr);
    if (ret == -1) {
        printf("pid:%d %s %d:shmctl error<%s>\n", getpid(), __FILE__, __LINE__, strerror(errno));
        return -1;
    }

    getchar();

    return 0;
}
